#include "Defs.h"
#include "Context.h"
#include "Utils.h"


Context_T::Context_T(PHTTP_FILTER_CONTEXT pFC, Rules_T * defaultRulesPtr)
	:isNewRequest(false)
	,isEntity(false)
	,entityLength(0)
	,rulesPtr(defaultRulesPtr)
{
	FillMemory(&urlInfo, sizeof(urlInfo), 0);
	FillMemory(&entityInfo, sizeof(entityInfo), 0);

	Utils_T::GetServerVariable(pFC, "REMOTE_ADDR", session.remoteAddr);
	Utils_T::GetServerVariable(pFC, "REMOTE_PORT", session.remotePort);
	Utils_T::GetServerVariable(pFC, "LOCAL_ADDR", session.localAddr);
	Utils_T::GetServerVariable(pFC, "SERVER_PORT", session.serverPort);
}

void Context_T::Reset(Rules_T * defaultRulesPtr)
{
	rulesPtr = defaultRulesPtr;
	isEntity = false;
	entityLength = 0;
	rawStream.Free();
	rawEntity.Free();
	request.Free();
}

void Context_T::Send404(PHTTP_FILTER_CONTEXT pFC)
{
	char szHeaders[MAX_PATH];
	char szDate[20];
	char szTime[20];
	unsigned int dataSize;

	SetLastError(NO_ERROR);

	GetDateFormat(
		MAKELCID(MAKELANGID(LANG_ENGLISH, SUBLANG_NEUTRAL), SORT_DEFAULT),
		0,
		NULL,
		"ddd',' dd MMM yyyy",
		szDate,
		sizeof(szDate) - 1);

	GetTimeFormat(
		MAKELCID(MAKELANGID(LANG_ENGLISH, SUBLANG_NEUTRAL), SORT_DEFAULT),
		0,
		NULL,
		"hh':'mm':'ss",
		szTime,
		sizeof(szTime) - 1);

	_snprintf(szHeaders, sizeof(szHeaders) - 1,
		"HTTP/1.1 404 Not Found\r\nDate: %s %s GMT\r\nContent-Length: %d\r\nContent-Type: text/html\r\nConnection: Close\r\nServer: %s\r\n\r\n",
		szDate,
		szTime,
		rulesPtr->rejectPageContent.Length(),
		rulesPtr->serverBanner.Ptr());

	dataSize = lstrlen(szHeaders);
	pFC->WriteClient(pFC, szHeaders, (LPDWORD)&dataSize, 0);

	dataSize = rulesPtr->rejectPageContent.Length();
	pFC->WriteClient(pFC, rulesPtr->rejectPageContent.Ptr(), (LPDWORD)&dataSize, 0);
}

void Context_T::Send404(LPEXTENSION_CONTROL_BLOCK pECB)
{
	char szRawHeaders[MAX_PATH];
	char szDate[20];
	char szTime[20];
	unsigned int dataSize;

	SetLastError(NO_ERROR);

	GetDateFormat(
		MAKELCID(MAKELANGID(LANG_ENGLISH, SUBLANG_NEUTRAL), SORT_DEFAULT),
		0,
		NULL,
		"ddd',' dd MMM yyyy",
		szDate,
		sizeof(szDate) - 1);

	GetTimeFormat(
		MAKELCID(MAKELANGID(LANG_ENGLISH, SUBLANG_NEUTRAL), SORT_DEFAULT),
		0,
		NULL,
		"hh':'mm':'ss",
		szTime,
		sizeof(szTime) - 1);

	_snprintf(szRawHeaders, sizeof(szRawHeaders) - 1,
		"HTTP/1.1 404 Not Found\r\nDate: %s %s GMT\r\nContent-Length: %d\r\nContent-Type: text/html\r\nConnection: Close\r\nServer: %s\r\n\r\n",
		szDate,
		szTime,
		rulesPtr->rejectPageContent.Length(),
		rulesPtr->serverBanner.Ptr());

	dataSize = lstrlen(szRawHeaders);
	pECB->WriteClient(pECB->ConnID, szRawHeaders, (LPDWORD)&dataSize, 0);

	dataSize = rulesPtr->rejectPageContent.Length();
	pECB->WriteClient(pECB->ConnID, rulesPtr->rejectPageContent.Ptr(), (LPDWORD)&dataSize, 0);
}